<?php

use Medoo\Medoo;
use QL\QueryList;

chdir(__DIR__);
require_once realpath('../..') . '/vendor/autoload.php';
$config = include '../database.php';


const BRAND = '奔驰';
//echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
$db->delete('charger', ['brand' => BRAND]);

//获取省份与城市
/*获取省份一级栏目
*{
    "id": 1,
    "name": "北京",
    "nameEn": "Beijing",
    "directCity": true  是否为直辖市
}*/
$pc_list = [];

$src_1 = "https://api.oneweb.mercedes-benz.com.cn/ow-piles-location/provinces?needFilterByPile=true";

$ql = QueryList::get($src_1);
$content = (string)$ql->getHtml();
$list_1 = json_decode($content, true);

//var_dump($list_1);die;
if ($list_1['message'] != 'success') {
    echo '获取省份一级栏目，错误';
    die;
}
//循环省份获取下属城市
foreach ($list_1['result'] as $k => $v) {

    if ($v['directCity']) {

        $pc_list[] = $v;

    } else {
        $p_id = $v['id'];
        $src_2 = "https://api.oneweb.mercedes-benz.com.cn/ow-piles-location/cities?needFilterByPile=true&provinceId=$p_id";

        $ql2 = QueryList::get($src_2);
        $content2 = (string)$ql2->getHtml();
        $city2 = json_decode($content2, true);
        if ($city2['message'] != 'success') {
            echo '获取城市二级栏目，错误' . '--' . $v['name'];
            continue;
        }

        foreach ($city2['result'] as $a => $b) {
            $pc_list[] = ['id' => $v['id'], 'name' => $v['name'], 'directCity' => false, 'id2' => $b['id'], 'name2' => $b['name']];
        }


    }
}

/*取出 省份-城市下 充电桩数据
*https://api.oneweb.mercedes-benz.com.cn/ow-piles-location/piles?city=%E7%8F%A0%E6%B5%B7%E5%B8%82&pageNum=1&pageSize=90000&longitude=&latitude=&keywords=
*/
$power = [];
foreach ($pc_list as $k => $v) {
    sleep(1);

    //直辖市
    if ($v['directCity']) {
        $c = urlencode($v['name']);
    } else {
        $c = urlencode($v['name2']);
    }
    $src_3 = "https://api.oneweb.mercedes-benz.com.cn/ow-piles-location/piles?city=$c&pageNum=1&pageSize=90000&longitude=&latitude=&keywords=";

    $ql3 = QueryList::get($src_3);
    $content3 = (string)$ql3->getHtml();
    $data = json_decode($content3, true);

    //当前城市 下充电桩取出失败
    if ($data['message'] != 'success' || !$data['result']) {
        continue;

    }

    foreach ($data['result'] as $item) {

        if (in_array($item['name'], $power)) {
            continue;

        }

        $power[] = $item['name'];

        $db->insert('charger', [
            'province' => $v['name'],
            'brand' => BRAND,
            'city' => $v['name2'] ?? $v['name'],
            'title' => $item['name'],
            'address' => $item['address'],
            'tel' => '',
            'lng' => $item['longitude'] ?? '',
            'lat' => $item['latitude'] ?? '',
        ]);
        echo "{$item['name']}完成" . PHP_EOL;
    }
}
echo '爬虫结束' . PHP_EOL;
